package com.summer_administration.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.summer_administration.mapper.ExpensesMapper;
import com.summer_administration.mapper.ExpensesMapper;
import com.summer_administration.mapper.GroupeMapper;
import com.summer_administration.pojo.*;
import com.summer_administration.pojo.Expenses;
import com.summer_administration.service.ExpensesService;
import com.summer_administration.service.ExpensesService;
import com.summer_administration.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ExpensesServiceImpl implements ExpensesService {
    @Autowired
    private ExpensesMapper expenseMapper;

    @Autowired
    private GroupeMapper groupeMapper;

    @Override
    public void add(Expenses expenses) {
        expenses.setCreateTime(LocalDateTime.now());
        expenses.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        expenses.setCreateUser(userId);
        // 新增一个根剧小组名字查询小组id
        String groupeName = expenses.getGroupName();
        String groupId = groupeMapper.findGroupIdByGroupName(groupeName);
        expenses.setGroupId(groupId);
        expenseMapper.add(expenses);
    }

    @Override
    public PageBean<Expenses> list(Integer pageNum, Integer pageSize) {
        PageBean<Expenses> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Page<Expenses> p = (Page<Expenses>) expenseMapper.list(userId);

        //pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public void update(Expenses expenses) {
        expenses.setUpdateTime(LocalDateTime.now());
        // 新增一个根剧小组名字查询小组id
        String groupeName = expenses.getGroupName();
        String groupId = groupeMapper.findGroupIdByGroupName(groupeName);
        expenses.setGroupId(groupId);
        expenseMapper.update(expenses);
    }

    @Override
    public void delete(Integer id) {
        expenseMapper.delete(id);
    }

    // 根据⼩组id统计⽀出⾦额
    @Override
    public List<GroupExpenseId> getGroupExpenses() {
        return expenseMapper.selectGroupExpenses();
    }

    //根据⽀付⽅式统计⽀出⾦额
    @Override
    public List<GroupExpenseDTO> getExpensesByMethod() {
        return expenseMapper.selectByMethod();
    }

    // 根据是否报销统计⽀出⾦额
    @Override
    public List<StateExpenseDTO> getExpensesByState() {
        return expenseMapper.selectByState();
    }
}